package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dto.UserLoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: test
 * @Create by: JJ菜菜
 * @Date: 2021/12/31 15:35
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    /**
     * 用户登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(UserLoginDto dto) {

        String phone = dto.getPhone();
        String password = dto.getPassword();
        // 1. 判断用户名是否为空, 如果不为空，就查询数据库
        if (StringUtils.isNotEmpty(phone) && StringUtils.isNotEmpty(password)){
            LambdaQueryWrapper<ApUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApUser::getPhone, phone);
            ApUser apUser = getOne(queryWrapper);
            if (apUser ==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }

            // 将数据库存的盐和前端输入的密码加盐进行md5加密
            String md5Pass = DigestUtils.md5DigestAsHex((password + apUser.getSalt()).getBytes());
            if (!apUser.getPassword().equals(md5Pass)){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }

            // 如果用户名密码正确，就生成token令牌，发送给前端
            String token = AppJwtUtil.getToken(apUser.getId().longValue());
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("token", token);
            resultMap.put("user", apUser);
            return ResponseResult.okResult(resultMap);
        }

        // 如果为空就是游客登录，直接将token返回前端
        String token = AppJwtUtil.getToken(0L);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        return ResponseResult.okResult(map);
    }
}
